﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Spring.Transaction.Interceptor;

using BOSS.Framework;
using BOSS.Framework.Search;
using BOSS.Framework.Search.Context;
using BOSS.Domain.Security;
using BOSS.Dao.Security;
using BOSS.Service.Security;


namespace BOSS.Service.Implements.Security
{
    /// <summary>
    /// 账号服务
    /// </summary>
    public class AccountService : EntityService<Account, int, IAccountDao>, IAccountService
    {
#if DEBUG
        private Account m_currentAccount;
#endif

        public Account CurrentAccount
        {
            get
            {
#if DEBUG
                if (System.Web.HttpContext.Current == null)
                {
                    return this.m_currentAccount;
                }
#endif

                LoginInfo loginInfo = LoginInfoRegistry.Instance.Current;
                return this.EntityDao.FindById(loginInfo.Account.Id);

                //return this.EntityDao.FindById(1);
            }

#if DEBUG
            set
            {
                this.m_currentAccount = value;
            }
#endif
        }

        /// <summary>
        /// 
        /// </summary>
        public IAccountPrivilegeSettingDao AccountPrivilegeSettingDao { get; set; }


        [Transaction(ReadOnly=false)]
        public void DoWorkflow() 
        { 
            
        }

        /// <summary>
        /// 保存或修改账户
        /// </summary>
        /// <param name="entity"></param>
        [Transaction(ReadOnly=false)]
        public override void SaveOrUpdate(Account entity)
        {
            this.Prepare(entity);

            if (entity.Id == 0)
            {
                entity.Password = PasswordCryptor.Default.Encrypt("111111");

                this.AccountPrivilegeSettingDao.Save(new AccountPrivilegeSetting() { Account = entity, Permission = PermissionType.ALLOW, PrivilegeName = PredefinedPrivileges.BOSS });
            }

            base.SaveOrUpdate(entity);
        }

        public Account FindByLoginName(string loginName)
        {
            return this.EntityDao.FindByLoginName(loginName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public Account FindByEmployeeId(string employeeId)
        {
            return this.EntityDao.FindByEmployeeId(employeeId);
        }

        private void Prepare<T>(T entity) where T : DomainEntity<int>
        {
            DateTime now = DateTime.Now;
            if (entity.Id == 0)
            {
                entity.Creator = this.CurrentAccount;                ;
                entity.CreateTime = now;
            }
            entity.Updator = this.CurrentAccount;
            entity.UpdateTime = now;
        }
    }
}
